/*
 * Thread.h
 *
 *  Created on: 2012-12-6
 *      Author: yangentao@gmail.com
 */

#ifndef THREAD_H_
#define THREAD_H_

#include <windows.h>
#include <boost/function.hpp>
namespace yet {


//dont call EndThread/TerminiteThread
//user can overide run method or assign OnRun with a boost function
//the default behavie of run method is call OnRun function if avaliable.
class Thread {
public:
	enum Priority{
		priorityLow = THREAD_PRIORITY_BELOW_NORMAL,
		priorityNormal = THREAD_PRIORITY_NORMAL,
		priorityHight = THREAD_PRIORITY_ABOVE_NORMAL,
	};
public:
	Thread();
	Thread(boost::function<int (void* arg)> onRun);
	virtual ~Thread();
public:
	bool isAlive();

	bool start();
	bool start(void* arg);
	bool start(void* arg , bool suspend);
	//return
	//true: thread end
	//false: timeout or abandoned by other process
	bool waitFinish(DWORD millSeconds = INFINITE);
	DWORD getThreadID();

	bool getExitCode(DWORD& code);
	void setPriority(Priority priority);
	void suspend();
	void resume();
	void postMessage(UINT msg, DWORD wParam = 0, DWORD lParam = 0);
	bool inThread();
protected:
	//user can overide this function
	//the default action is call OnRun
	int run(void* argp);
private:
	void init();
public:
	//which function to run
	boost::function<int (void* arg)> OnRun;
	//call after OnRun, but the thread is not exit
	boost::function<void (void* arg, int returnCode)> OnRunReturn;
protected:
	Priority priority;
	void* argp;
	HANDLE threadHandle;
	DWORD threadId;

	friend DWORD WINAPI __MyThreadProc(LPVOID arg);
};

} /* namespace yet */
#endif /* THREAD_H_ */
